'''
Copyright: 
Descripttion: 
version: 
Author: chengx
Date: 2022-02-18 09:05:18
LastEditors: chengx
LastEditTime: 2022-03-13 11:41:13
'''
from wsgiref.simple_server import sys_version
import lightgbm as lgb
from lightgbm import plot_importance
import numpy as np
from numpy.lib.function_base import delete
from sklearn.metrics import mean_squared_error,accuracy_score
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from matplotlib import  pyplot as plt
import scipy.signal
from sklearn import metrics
from sklearn.metrics import classification_report
from sklearn.metrics import cohen_kappa_score
import seaborn as sns

# 加载数据
def readHsi():
    # blx = np.load('./data/blx.npy')
    # blt = np.load('./data/blt.npy')
    # njx = np.load('./data/njx.npy')
    # x = np.concatenate((blx,blt,njx),axis=0)
    # # x[[50,150],:]=x[[150,50],:]
    # # print('X',blx.shape,blt.shape,njx.shape,x.shape)
    # y1 = np.zeros((blx.shape[0]))
    # y2 = np.ones(blt.shape[0])
    # y3 = np.ones((njx.shape[0]))*2
    # y = np.concatenate((y1,y2,y3),axis=0)


    x= np.load('./data/x.npy')[:,0:180]
    y= np.load('./data/y.npy')
    print('read data',x.shape,y.shape)

    # 归一化
    # for i in range(x.shape[1]):
    #     fm = np.max(x[:,i])-np.min(x[:,i])
    #     x[:,i] = (x[:,i] - float(np.min(x[:,i])))
    #     x[:,i] = x[:,i]/fm
    # x = scipy.signal.savgol_filter(x, 9, 2, deriv=1)  # 一阶导数处理

    return x,y

def modelFit(x_train, y_train,x_test, y_test):
    gbm = lgb.LGBMClassifier(silent=True)
    gbm.fit(x_train, y_train, eval_set=[(x_test, y_test)], eval_metric='multi_logloss', early_stopping_rounds=10)

    # 测试集预测
    y_pred = gbm.predict(x_test, num_iteration=gbm.best_iteration_)

    # 模型评估
    OA = accuracy_score(y_test, y_pred)
    print('The OA of prediction is:', OA)

    kappa = cohen_kappa_score(y_test, y_pred)
    print('kappa train',kappa)

    # 混淆矩阵
    # M = metrics.confusion_matrix(y_test,y_pred)
    # print(M)
    # 生成分类报告
    classification = classification_report(y_test, y_pred) #, digits=4
    print(classification)

    return gbm


def weightPic(coff_10runs): # 注意力权重图
    x_range = range(180)

    fig = plt.figure()
    ax2 = fig.add_subplot(911)
    ax2.plot(x_range, coff_10runs[0,:].reshape((180)), color='blue')
    ax3 = fig.add_subplot(912)
    ax3.plot(x_range, coff_10runs[1,:].reshape((180)), color='blue')
    ax4 = fig.add_subplot(913)
    ax4.plot(x_range, coff_10runs[2, :].reshape((180)), color='blue')
    ax5 = fig.add_subplot(914)
    ax5.plot(x_range, coff_10runs[3, :].reshape((180)), color='r')
    ax6 = fig.add_subplot(915)
    ax6.plot(x_range, coff_10runs[4, :].reshape((180)), color='blue')
    ax7 = fig.add_subplot(916)
    ax7.plot(x_range, coff_10runs[5, :].reshape((180)), color='blue')
    ax8 = fig.add_subplot(917)
    ax8.plot(x_range, coff_10runs[6, :].reshape((180)), color='blue')
    ax9 = fig.add_subplot(918)
    ax9.plot(x_range, coff_10runs[7, :].reshape((180)), color='blue')
    ax10 = fig.add_subplot(919)
    ax10.plot(x_range, coff_10runs[8,:].reshape((180)), color='blue')
    plt.xticks([0,45,90,135,180],[490,595,700,805,910])
    plt.draw()
    plt.show()


def weightHotPic(coff_10runs):# 注意力权重热图
    print(coff_10runs.shape)
    a = []
    for k in range(10):
        g = coff_10runs[k,:].reshape(-1)
        g = g/10
        fm = np.max(g)-np.min(g)
        for i in range(g.shape[0]):
            g[i] = float(g[i]-np.min(g))/fm
            if g[i]>=1:
                g[i] = 1
            a.append(g)
    x = np.array(a)


    sns.set()
    fig=plt.figure(figsize=(18,8))

    plt.contourf(x)
    cb=plt.colorbar(aspect = 10 )
    cb.ax.tick_params(labelsize=22)
    cb.set_ticks([0,0.5,0.75,1])
    font1 = {'family': 'Times New Roman',
    'size': 24,
    }
    plt.xticks([0,45,90,135,180],[1000,1150,1300,1450,1600])
    plt.yticks([])
    plt.tick_params(labelsize=22)# 设置坐标轴的字体大小
    plt.xlabel("Wavelength/nm",font1)
    plt.tick_params(labelsize=22)
    plt.show()

if __name__ == '__main__':
    
    # weight= []
    # x,y = readHsi()
    # for i in range(20,85,5):
    #     print("ratio",i)
    #     # i = i/100
    #     x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8,random_state=i)
    #     gbm = modelFit(x_train, y_train,x_test, y_test)

        
    #     w = gbm.feature_importances_
    #     # w = w[30:210]
    #     weight.append(w)
    # weight = np.array(weight)
    
    
    a = np.load('./result/gbdtW2.npy')
    # print('a shape:',a.shape)
    # weightPic(weight)
    # np.save('./result/gbdtW2.npy',weight)
    weightHotPic(a)


